package com.hl.lib.utils

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build


object AlarmUtils {

    /**
     * triggerAtMillis:闹钟响的时候
     */
    fun setExactAlarm(
        context: Context,
        triggerAtMillis: Long,
        intent: Intent,
        requestCode: Int
    ): Pair<AlarmManager, PendingIntent> {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val pendingIntent = getPendingIntent(context, intent, requestCode)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP,
                triggerAtMillis,
                pendingIntent
            )
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(
                AlarmManager.RTC_WAKEUP,
                triggerAtMillis,
                pendingIntent
            )
        } else {
            alarmManager[AlarmManager.RTC_WAKEUP, triggerAtMillis] =
                pendingIntent
        }
        return Pair(alarmManager, pendingIntent)
    }

    private fun getPendingIntent(
        context: Context,
        intent: Intent,
        requestCode: Int
    ): PendingIntent {
        return PendingIntent.getBroadcast(
            context,
            requestCode,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )
    }
}